package com.blueheart.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@Slf4j
@Component
public class WebClient extends RestTemplate implements RestOperations {

    public WebClient() {
        super();
        this.setRequestFactory(getClientHttpRequestFactory());
    }


    public WebClient(final List<HttpMessageConverter<?>> messageConverters) {
        super(messageConverters);
        this.setRequestFactory(getClientHttpRequestFactory());
    }

    private static ClientHttpRequestFactory getClientHttpRequestFactory() {
        int timeout = 5000;
        RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build();
        CloseableHttpClient client = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(config)
            .build();
        return new HttpComponentsClientHttpRequestFactory(client);
    }

}
